package com.xianbeiying.app.ckgl.activity;

import org.MediaPlayer.PlayM4.Player;

import android.os.AsyncTask;
import android.os.Bundle;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.view.SurfaceView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lidroid.xutils.util.LogUtils;
import com.xianbeiying.app.ckgl.MyApplication;
import com.xianbeiying.app.ckgl.R;
import com.xianbeiying.app.ckgl.adapter.ReTimeMontiorAdapter;
import com.xianbeiying.app.ckgl.bean.DevicesBean;
import com.xianbeiying.app.ckgl.bean.RealTimeMtBean;
import com.xianbeiying.app.ckgl.bean.UrlBean;
import com.xianbeiying.app.ckgl.http.HttpCallBackUtil;
import com.xianbeiying.app.ckgl.model.GetModel;
import com.xianbeiying.app.ckgl.model.ImageModel;
import com.xianbeiying.app.ckgl.photo.activity.HistoryPictureActivity;
import com.xianbeiying.app.ckgl.util.ToastUtil;
import com.xianbeiying.app.ckgl.widght.dapengView.DpView;
import com.xianbeiying.app.ckgl.widght.dapengView.Dpdata;

import com.hikvision.netsdk.ExceptionCallBack;
import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.NET_DVR_CLIENTINFO;
import com.hikvision.netsdk.NET_DVR_DEVICEINFO_V30;
import com.hikvision.netsdk.NET_DVR_IPPARACFG_V40;
import com.hikvision.netsdk.RealPlayCallBack;

import java.util.ArrayList;
import java.util.List;

/**
 * 实时监控
 **/
public class RealTimeMonitorActivity extends BaseActivity implements View.OnClickListener, Dpdata, HttpCallBackUtil {
    private ImageView iv_title_left;
    private TextView tv_title;
    private ListView rtime_mtlist;
    //水平滑动的
    private LinearLayout ly_rtmt_horizontal;
    private View va_line;
    private TextView tv_va_all;
    private DpView dpView;
    private GetModel getModel;
    //历史查询
    private Button btn_lscx;
    private ReTimeMontiorAdapter reTimeMontiorAdapter;
    private ImageModel imageModel;

    private SurfaceView surface;

    private int playPort = -1;
    private static final int PLAYING_BUFFER_SIZE = 1024 * 1024 * 4;
    private Player player;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_real_time_monitor);
        initView();
        surface = (SurfaceView) findViewById( R.id.surfaceMonitor );
        new LoadingDevicesTask().execute();
    }

    private void initView() {
        ly_rtmt_horizontal = (LinearLayout) findViewById(R.id.ly_rtmt_horizontal);
        va_line = (View) findViewById(R.id.va_line);
        tv_va_all = (TextView) findViewById(R.id.tv_va_all);
        iv_title_left = (ImageView) findViewById(R.id.iv_title_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("实时监控");
        rtime_mtlist = (ListView) findViewById(R.id.rtime_mtlist);
        btn_lscx = (Button) findViewById(R.id.btn_lscx);
        getModel = new GetModel(this);
        getModel.addResponseListener(this);
        imageModel = new ImageModel(this);
        imageModel.addResponseListener(this);
        imageModel.ImageHistoLogins(com.xianbeiying.app.ckgl.util.DataUtil.getLoactionTime(), MyApplication.devicesBean.getGREENHOUSE().get(0).getGreenhouseId(), true);
        initData();
        initEvent();
    }

    private void initData() {
        if (MyApplication.devicesBean != null) {
            devicesBean = MyApplication.devicesBean;
            getData(devicesBean.getGREENHOUSE(), devicesBean.getGREENHOUSE().size(), 0);
            LogUtils.e("==================");
            getModel.QUERY_CROPSTEP("QUERY_CROPSTEP", devicesBean.getGREENHOUSE().get(0).getGreenhouseId(), true);
        } else {
            //获取大棚数据
            getModel.QUWEYDEVS(true);
        }
    }

    private void initEvent() {
        tv_va_all.setOnClickListener(this);
        iv_title_left.setOnClickListener(this);
        btn_lscx.setOnClickListener(this);
    }

    private void getData(List<DevicesBean.GREENHOUSEBean> DEVICES, int size, final int id) {
        dpView = new DpView(DEVICES, size, id, ly_rtmt_horizontal, this);
        dpView.setDpdata();
        dpView.addResponseListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tv_va_all:
                tv_va_all.setVisibility(View.GONE);
                va_line.setVisibility(View.GONE);
                break;
            //历史查询
            case R.id.btn_lscx:
//                ToastUtil.showInfo(RealTimeMonitorActivity.this,"暂未开通");
                startActivity(new Intent(RealTimeMonitorActivity.this, HistoryPictureActivity.class).putExtra("id", devicesBean.getGREENHOUSE().get(faId).getGreenhouseId()));
                break;
        }
    }

    private int faId;

    @Override
    public void onDpdata(int sid, boolean isChoice) {
        if (isChoice) {
            faId = sid;
            getModel.QUERY_CROPSTEP("QUERY_CROPSTEP", devicesBean.getGREENHOUSE().get(faId).getGreenhouseId(), true);
        }
    }

    //网络返回值
    private DevicesBean devicesBean;
    private RealTimeMtBean realTimeMtBean;
    List<String> imgUrl = new ArrayList<>();

    @Override
    public void onCallBackData(String url, Object content) {
        if (url.equals(UrlBean.QUWEYDEVS)) {
            if (content != null) {
                devicesBean = JSON.parseObject(new String((byte[]) content), DevicesBean.class);
                MyApplication.devicesBean = devicesBean;
                getData(devicesBean.getGREENHOUSE(), devicesBean.getGREENHOUSE().size(), 0);
                //实时监控信息
                getModel.QUERY_CROPSTEP("QUERY_CROPSTEP", devicesBean.getGREENHOUSE().get(faId).getGreenhouseId(), true);
            }
        }
        if (url.equals("实时监控信息")) {
            if (content != null) {
                realTimeMtBean = JSON.parseObject(new String((byte[]) content), RealTimeMtBean.class);
                if (realTimeMtBean.isR()) {
                    if (realTimeMtBean.getV().getCROPS().size() != 0) {
                        if (imgUrl!=null&&imgUrl.size()!= 0){
                            reTimeMontiorAdapter = new ReTimeMontiorAdapter(this, realTimeMtBean, imgUrl.get(0));
                        } else {
                            reTimeMontiorAdapter = new ReTimeMontiorAdapter(this, realTimeMtBean, "");
                        }
                        rtime_mtlist.setAdapter(reTimeMontiorAdapter);
                    }
                } else {
                    rtime_mtlist.setAdapter(null);
                    ToastUtil.showInfo(RealTimeMonitorActivity.this, realTimeMtBean.getERR_MSG());

                }
            }
        }
        if (url.equals("历史图片")) {
            imgUrl.clear();
            JSONArray jsonArray = JSON.parseArray(content + "");
            if (jsonArray != null && jsonArray.size() != 0) {
                int size = jsonArray.size();
                for (int i = 0; i < size; i++) {
                    imgUrl.add(jsonArray.getString(i));
                }
            }
        }
    }
    private ExceptionCallBack exceptionCallback = new ExceptionCallBack() {

        @Override
        public void fExceptionCallBack(int code, int userId, int handle) {
            System.out.println(
                    String.format(
                            "ExceptionCallBack::fExceptionCallBack( 0x%h, %s, %s )", code, userId, handle ) );
        }
    };
    private class LoadingDevicesTask extends AsyncTask{

        private HCNetSDK hcNetSdk;
        @Override
        protected Object doInBackground(Object... params) {

            try
            {
                final long begin = System.currentTimeMillis();

                player = Player.getInstance();
                hcNetSdk = new HCNetSDK();

                hcNetSdk.NET_DVR_Init();

                hcNetSdk.NET_DVR_SetConnectTime( Integer.MAX_VALUE );

                hcNetSdk.NET_DVR_SetExceptionCallBack( exceptionCallback );

//			DeviceInfo device = globalAppManager.getDeviceList().get( 0 );

                // ----------------------------------------------------------------

                // get play port
                playPort = player.getPort();

                // ----------------------------------------------------------------

                NET_DVR_DEVICEINFO_V30 dvr_deviceinfo = new NET_DVR_DEVICEINFO_V30();
                // "Hangzhou, China", "", 1, "115.236.50.5", 8800, "guest", "guest4500"
                int userId = hcNetSdk.NET_DVR_Login_V30(
                        "192.168.1.193", 8000,
                        "admin", "ts123456",
                        dvr_deviceinfo );

//	        DebugTools.dump( dvr_deviceinfo );

//	        System.out.println( "DeviceConfig: " + device.getAddress() + " " + device.getPort() + " "
//	        		+ device.getUserName() + " " + device.getPassword() );

                System.out.println( "Attempting to login: userId " + userId );
                System.out.println(
                        String.format( "DeviceInfo: byChanNum=%s, byIPChanNum=%s",
                                dvr_deviceinfo.byChanNum, dvr_deviceinfo.byIPChanNum ) );

//	        catchErrorIfNecessary();
                NET_DVR_IPPARACFG_V40 ipParaCfg = new NET_DVR_IPPARACFG_V40();

                // UserId, Command, ChannelNo., Out
                hcNetSdk.NET_DVR_GetDVRConfig( userId, HCNetSDK.NET_DVR_GET_IPPARACFG_V40, 0, ipParaCfg );
//	        System.out.println(
//	        		String.format( "NET_DVR_IPPARACFG_V40{ dwAChanNum : %s, dwDChanNum : %s, dwGroupNum : %s, dwStartDChan : %s }",
//	        				ipParaCfg.dwAChanNum, ipParaCfg.dwDChanNum,
//	        				ipParaCfg.dwGroupNum, ipParaCfg.dwStartDChan ) );

                int counter = 0;
//	        for ( byte byt : ipParaCfg.byAnalogChanEnable ) {
//	        	if ( CHANNEL_ENABLED == byt ) counter++;
//	        }
//	        System.out.println( "AnalogChanEnabledSize: " + counter );

                System.out.println( "-------------------------------------" );

//	        for ( NET_DVR_IPCHANINFO entry : ipParaCfg.struIPChanInfo ) {
//	        	if ( CHANNEL_ENABLED == entry.byEnable ) {
//	        		DebugTools.dump( entry );
//	        	}
//	        }

//	        System.out.println( "-------------------------------------" );
//
//	        for ( NET_DVR_IPDEVINFO_V31 entry : ipParaCfg.struIPDevInfo ) {
//
//	        	if ( 1 == entry.byEnable ) {
//	        		// byProType
//	        		// Protocol type: 0- private (default), 1- Panasonic, 2- sony, get more NET_DVR_GetIPCProtoList銆�
//
//	        		//DebugTools.dump( entry );
//
//	        		System.out.println( "{" );
//		        	System.out.println( "  byDomain -> " + new String( Utility.getValidByte( entry.byDomain ) ) );
//		        	System.out.println( "  struIP.sIpV4 -> " + new String( Utility.getValidByte( entry.struIP.sIpV4 ) ) );
//		        	System.out.println( "  sUserName -> " + new String( Utility.getValidByte( entry.sUserName ) ) );
//		        	System.out.println( "  sPassword -> " + new String( Utility.getValidByte( entry.sPassword ) ) );
//		        	System.out.println( "  byProType -> " + entry.byProType );
//		        	System.out.println( "  wDVRPort -> " + entry.wDVRPort );
//		        	System.out.println( "}" );
//	        	}
//	        }
//	        System.out.println( "-------------------------------------" );


//	        DebugTools.dump( ipParaCfg );
//	        catchErrorIfNecessary();


                // ----------------------------------------------------------------

                NET_DVR_CLIENTINFO clientInfo = new NET_DVR_CLIENTINFO();
//	        ArrayList<ChannelInfo> channelList = device.getChannelList();
//	        System.out.println( "ChannelList: " + channelList.size() );
//	        DebugTools.dump( channelList.get( 0 ) );

//	        clientInfo.lChannel = 4;
                clientInfo.lChannel = 34;

//	        clientInfo.lLinkMode = 1;
                clientInfo.lLinkMode = 0;
//	        clientInfo.lLinkMode = 0x80000000;
                clientInfo.sMultiCastIP = null;

                // UserId, ClientInfo, RealplayCallback, Blocked
                final int returned = hcNetSdk.NET_DVR_RealPlay_V30( userId, clientInfo, realplayCallback, true );
                System.out.println( "Living: " + returned );
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

//	        catchErrorIfNecessary();

            return null;

            // LiveControl liveCtrl = new LiveControl( this );

        }
    }
    private RealPlayCallBack realplayCallback = new RealPlayCallBack() {

        @Override
        public void fRealDataCallBack(int handle, int dataType, byte[] buffer, int bufferSize) {
            System.out.println( String.format( "fRealDataCallBack{ handle : %s, dataType : %s, bufferSize : %s }",
                    handle, dataType, bufferSize ) );

            int i = 0;

            switch ( dataType ) {
                case HCNetSDK.NET_DVR_SYSHEAD:

                    if ( -1 == (playPort = Player.getInstance().getPort() ) ) {
                        System.out.println( "Can't get play port!" );

                        return;
                    }

                    if ( 0 < bufferSize ) {
                        if ( openPlayer( buffer, bufferSize ) ) {
                            System.out.println( "Open player successfully." );
                        } else {
                            System.out.println( "Open player failed." );
                        }
                    }

                    break;

                case HCNetSDK.NET_DVR_STREAMDATA:
                case HCNetSDK.NET_DVR_STD_VIDEODATA:
                case HCNetSDK.NET_DVR_STD_AUDIODATA:

                    if ( 0 < bufferSize && -1 != playPort ) {
                        try {
                            for ( i = 0; i < 400; i++) {
                                if ( Player.getInstance().inputData( playPort, buffer,
                                        bufferSize ) ) {
                                    System.out.println( "Played successfully." );
                                    break;
                                }

                                System.out.println( "Playing failed." );

                                Thread.sleep( 10 );
                            }
                        } catch (Exception e) {

                        }

                        if ( i == 400 ) {
                            System.out.println( "inputData failed" );
                        }

//					if ( Player.getInstance().inputData( playPort, buffer, bufferSize ) ) {
//						System.out.println( "Played successfully." );
//					} else {
//						System.out.println( "Playing failed." );
//					}
                    }

//				if ( -1 != playPort ) {
//					// closing the player
//				}
//
//				if ( openPlayer( buffer, bufferSize ) ) {
//
//				}
            }

            //if ( -1 == playPort ) return;

            //Player.getInstance().inputData( playPort, buffer, bufferSize );
        }
    };

    private boolean openPlayer(byte[] buffer, int bufferSize) {

//		do {
//			playPort = Player.getInstance().getPort();
//		} while ( -1 == playPort );

        if ( ! Player.getInstance().setStreamOpenMode(playPort, Player.STREAM_FILE ) ) {
            System.out.println( "The player set stream mode failed!" );
            return false;
        }

        if ( ! Player.getInstance().openStream( playPort, buffer, bufferSize, PLAYING_BUFFER_SIZE ) ) {
            Player.getInstance().freePort( playPort );
            playPort = -1;

            return false;
        }

        Player.getInstance().setStreamOpenMode( playPort, Player.STREAM_FILE );

        System.out.println( "We are using " + surface.getHolder() + " as a Displayer." );

        if ( ! Player.getInstance().play( playPort, surface.getHolder().getSurface() ) ) {
            Player.getInstance().closeStream( playPort );
            Player.getInstance().freePort( playPort );

            playPort = -1;

            return false;
        }

        return true;
    }
}
